<?php

namespace App\Http\Controllers;

use Auth;
use Socialite;
use App\Repositories\WechatLoginRepository;

class AuthController extends Controller
{
    protected $wechatLoginRepository;

    public function __construct(WechatLoginRepository $wechatLoginRepository)
    {
        $this->wechatLoginRepository = $wechatLoginRepository;
    }

    public function redirectToProvider($driver = 'wechat')
    {
        return Socialite::driver($driver)->redirect();
    }

    public function handleProviderCallback($driver = 'wechat')
    {
        $user = Socialite::driver($driver)->user();

        $user = $this->wechatLoginRepository->attemptUserinfoLogin($user);

        if ($user) {
            Auth::login($user);
            return redirect()->route('write.home');
        } else {
            return abort('500', '服务器忙，请稍后再试');
        }
    }
}
